<%@ page language="java" import="java.lang.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<div class="row-fluid" style="height: inherit;margin:0px;border: 0px">
	<form id="setsForm" class="form-horizontal" target="_ifr" style="margin-right:10px;">
		<input type="hidden" id="id" name="id" value="${distribution.id}" />
		<input type="hidden" id="state" name="state" value="${distribution.state}" />
		<div class="row" style="margin:0;padding:0;">
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="outNo">任务单号：</label>
				<div class="controls">
					<div class="input-append span12">
						<c:choose>
							<c:when test="${edit==1}">
								<input type="text" class="span11" id="taskNo" name="taskNo" value="${distribution.taskNo }" placeholder="任务单号" readonly="readonly" />
							</c:when>
							<c:otherwise>
								<input type="text" class="span11" id="taskNo" name="taskNo" placeholder="后台自动生成" readonly="readonly" />
							</c:otherwise>
						</c:choose>
					</div>
				</div>
			</div>
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="operateTime">操作时间：</label>
				<div class="controls">
					<div class="input-append span12 required">
						<input type="text" class="form-control date-picker" id="startTime" name="startTime" style="width:220px;" value="${distribution.startTime }" placeholder="操作时间" />
					</div>
				</div>
			</div>			
		</div>		
		<div class="row" style="margin:0;padding:0;">
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="carId">配送小车：</label>
				<div class="controls">
					<div class="span12 required" style="float: none !important;">
						<input id="carId" name="carId" class="span11" type="text" placeholder="配送小车" />
					</div>
				</div>
			</div>
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="userId">操作人：</label>
				<div class="controls">
					<div class="span12 required" style="float: none !important;">
						<input type="text" class="span11" name="userId" id="userId" placeholder="操作人" value="${distribution.userId}" />
					</div>
				</div>
			</div>
		</div>
		<div class="row" style="margin:0;padding:0;">
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="remark">备注：</label>
				<div class="controls">
					<div class="input-append span12">
						<input type="text" class="span11" name="remark" id="remark" placeholder="备注" value="${distribution.remark}" />
					</div>
				</div>
			</div>
		</div>
		<div style="margin-left:10px;">
			<span class="btn btn-info" id="formSave" onclick="saveForm();">
				<i class="ace-icon fa fa-check bigger-110"></i>保存
			</span>
			<span class="btn btn-info" id="publish" onclick="submit();">
				<i class="ace-icon fa fa-check bigger-110"></i>提交
			</span>
		</div>
	</form>
	<div id="materialDiv" style="margin:10px;">
		<!-- 下拉框 -->
		<label class="inline" for="routeId">配送工位：</label>
		<input type="text" id = "routeId" name="routeId" style="width:150px;margin-right:10px;" />	
		<!-- 下拉框 -->
		<label class="inline" for="setsInfor">套件：</label> 
		    <input type="text" id="setsInfor" name="setsInfor" style="width:350px;margin-right:10px;" />
		<button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
			<i class="icon-plus" style="margin-right:6px;"></i>添加
		</button>
	</div>
	<!-- 表格div -->
	<div id="grid-div-c" style="width:100%;margin:0px auto;">
		<!-- 	表格工具栏 -->
		<div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
			<div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
		</div>
		<!-- 物料详情信息表格 -->
		<table id="grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
$(".date-picker").datetimepicker({format: "YYYY-MM-DD HH:mm:ss",useMinutes:true,useSeconds:true});
$("#setsForm").validate({
   ignore: "", 
   rules:{
      "carId":{
         required:true
      },
      "userId":{
         required:true
      }
   },
   messages: {
      "carId":{
         required:"请选择配送小车！"
      },
      "userId":{
         required:"请选择操作人！"
      }     
   },
   errorClass: "help-inline",
   errorElement: "span",
   highlight:function(element, errorClass, validClass) {
       $(element).parents(".control-group").addClass("error");
   },
   unhighlight: function(element, errorClass, validClass) {
       $(element).parents(".control-group").removeClass("error");
   }
});

function saveForm() {
    var bean = $("#setsForm").serialize();
    if ($("#setsForm").valid()) {
        savaSets(bean);
    }     
}
$("#routeId").select2({
			placeholder : "请选择工位",//文本框的提示信息
			minimumInputLength : 0, //至少输入n个字符，才去加载数据
			allowClear : true, //是否允许用户清除文本信息
			multiple: false,
			closeOnSelect:false,
			ajax : {
				url : context_path + '/artBom/getRoute',
				dataType : 'json',
				delay : 250,
				data : function(term, pageNo) { //在查询时向服务器端传输的数据
					term = $.trim(term);
					selectParam = term;
					return {
						/* docId : $("#baseInfor #id").val(), */
						queryString : term, //联动查询的字符
						pageSize : 15, //一次性加载的数据条数
						pageNo : pageNo, //页码
						time : new Date(),
					}
				},
				results : function(data, pageNo) {
					var res = data.result;
					if (res.length > 0) { //如果没有查询到数据，将会返回空串
						var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
						return {
							results : res,
							more : more
						};
					} else {
						return {
							results : {
								"id" : "0",
								"text" : "没有更多结果"
							}
						};
					}

				},
				cache : true
			}
		});
		$("#setsForm #carId").select2({
			placeholder : "请选择配送小车",//文本框的提示信息
			minimumInputLength : 0, //至少输入n个字符，才去加载数据
			allowClear : true, //是否允许用户清除文本信息
			multiple: false,
			closeOnSelect:false,
			width:200,
			ajax : {
				url : context_path + "/setPull/getCarSelect",
				dataType : "json",
				delay : 250,
				data : function(term, pageNo) {
					term = $.trim(term);
					selectParam = term;
					return {
						queryString : term,
						pageSize : 15,
						pageNo : pageNo,
						time : new Date(),
					}
				},
				results : function(data, pageNo) {
					var res = data.result;
					if (res.length > 0) {
						var more = (pageNo * 15) < data.total;
						return {
							results : res,
							more : more
						};
					} else {
						return {
							results : {
								"id" : "0",
								"text" : "没有更多结果"
							}
						};
					}

				},
				cache : true
			}
		}); 
function savaSets(bean) {
        $.ajax({
			url : context_path + "/setPull/saveSets.do",
			type : "POST",
			data : bean,
			dataType : "JSON",
			success : function(data) {
				if (Boolean(data.result)) {
					layer.msg("表头保存成功！", {icon : 1});
					$("#setsForm #taskNo").val(data.taskNo);
					$("#setsForm #id").val(data.setId);
					$("#setsForm #state").val(data.state);
					$("#grid-table").jqGrid("setGridParam", {
                       postData: {queryJsonString:""}
                    }).trigger("reloadGrid");
				} else {
					layer.alert(data.msg, {icon : 2});
				}
			},
			error : function(XMLHttpRequest) {
				alert(XMLHttpRequest.readyState);
				alert("出错啦！！！");
			}
		});
    }
	var editFunction = function eidtSuccess(XHR){
		 var data = eval("("+XHR.responseText+")"); 
		if(data["msg"]!=""){
			layer.alert(data["msg"]);
		}
		jQuery("#grid-table-c").jqGrid('setGridParam', 
				{
					postData: {
						id:$('#id').val(),
						queryJsonString:""
					} 
				}
		  ).trigger("reloadGrid");
	};
	
  
  	_grid_detail=jQuery("#grid-table-c").jqGrid({
         url : context_path + "/setPull/detailList.do?pId="+$("#setsForm #id").val(),
         datatype : "json",
         colNames : [ "详情主键","套件编号","套件名称","数量","配送工位"],
         colModel : [ 
  					  {name : "id",index : "id",width : 20,hidden:true}, 
  					  {name : "suiteNo",index:"suiteNo",width :20}, 
                      {name : "suiteName",index:"suiteName",width : 20},
                      {name : "amount", index: "amount", width: 20,editable : true,editrules: {custom: true, custom_func: numberRegex},
                        editoptions: {
	                          size: 25,
	                          dataEvents: [
	                              {
	                                  type: "blur",     //blur,focus,change.............
	                                  fn: function (e) {
	                                	  var $element = e.currentTarget;
	                                	  var $elementId = $element.id;
	                                	  var rowid = $elementId.split("_")[0];
	                                	  var id=$element.parentElement.parentElement.children[1].textContent;
	                                	  var indocType = 1;
	                                	  var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
	                                	  if (!reg.test($("#"+$elementId).val())) {
	                                		  layer.alert("请输入正实数！(注：小数点后将舍去)");
	                                		  return;
	                                	   }
	                                	  $.ajax({
	                                		  url:context_path + "/setPull/setAmount",
	                                		  type:"POST",
	                                		  data:{id:id,amount:$("#"+rowid+"_amount").val()},
	                                		  dataType:"json",
	                                		  success:function(data){
	                                		        if(Boolean(data.result)){
	                                		           $("#grid-table-c").jqGrid("setGridParam", 
                                							{
                                					    		url : context_path + "/setPull/detailList.do?pId="+$("#setsForm #id").val(),
                                								postData: {queryJsonString:""} //发送数据  :选中的节点
                                							}
                                					  ).trigger("reloadGrid");
                                					  layer.msg("保存数量成功！");
	                                		        }else{
	                                		        layer.alert(data.msg);
	                                		        }	                                		                     		      
	                                		  }
	                                	  }); 
	                                  }
	                              }
	                          ]
	                      }
                      },
                      {name : "routeName",index:"routeName",width : 20},
                ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : "#grid-pager-c",
         sortname : "dd.id",
         sortorder : "desc",
         altRows: true,
         viewrecords : true,
         autowidth:true,
         multiselect:true,
		 multiboxonly: true,
         beforeRequest:function (){
            dynamicGetColumns(dynamicDefalutValue,"grid-table-c", $(window).width()-$("#sidebar").width() -7);
            //重新加载列属性
         },
         loadComplete : function(data){
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
             $(window).triggerHandler("resize.jqGrid");
         },
	   cellEdit: true,
	   cellsubmit : "clientArray",
  	   emptyrecords: "没有相关记录",
  	   loadtext: "加载中...",
  	   pgtext : "页码 {0} / {1}页",
  	   recordtext: "显示 {0} - {1}共{2}条数据",
    });
  	$(window).on("resize.jqGrid", function () {
  		$("#grid-table-c").jqGrid( "setGridWidth", $("#grid-div-c").width() - 3 );
  		var height = $(".layui-layer-title",_grid_detail.parents(".layui-layer")).height()+
                     $("#setsForm").outerHeight(true)+$("#materialDiv").outerHeight(true)+
                     $("#grid-pager-c").outerHeight(true)+$("#fixed_tool_div.fixed_tool_div.detailToolBar").outerHeight(true)+
                   //$("#gview_grid-table-c .ui-jqgrid-titlebar").outerHeight(true)+
                     $("#gview_grid-table-c .ui-jqgrid-hbox").outerHeight(true);
                     $("#grid-table-c").jqGrid('setGridHeight',_grid_detail.parents(".layui-layer").height()-height);
  	});
  	$(window).triggerHandler("resize.jqGrid"); 
//将数据格式化成两位小数：四舍五入
 function formatterNumToFixed(value,options,rowObj){
	if(value!=null){
		var floatNum = parseFloat(value);
		return floatNum.toFixed(2);
	}else{
		return "0.00";
	}
 } 
 //数量输入验证
function numberRegex(value, colname) {
    var regex = /^\d+\.?\d{0,2}$/;
    reloadDetailTableList();
    if (!regex.test(value)) {
        return [false, ""];
    }
    else  return [true, ""];
}

//添加套件详情
 function addDetail(){
	  if($("#setsForm #id").val()==""){
		  layer.alert("请先保存表单信息！");
		  return;
	  }
	  if($("#routeId").val()==""){
	      layer.alert("请选择配送工位！");
		  return;
	  }
	  if($("#setsInfor").val()==""){
	      layer.alert("请选择套件！");
		  return;
	  }
	  if($("#setsForm #state").val()=="0"||$("#setsForm #state").val()==""){
		  //将选中的套件和工位添加到数据库中
		  $.ajax({
			  type:"POST",
			  url:context_path + "/setPull/saveDetail.do",
			  data:{pId:$("#setsForm #id").val(),routeId:$("#routeId").val(),suiteId:$("#setsInfor").val()},
			  dataType:"json",
			  success:function(data){
				  if(Boolean(data.result)){
					 layer.msg("添加成功",{icon:1,time:1200});
					  //重新加载详情表格
					 reloadDetailTableList();
					 $("#setsForm #hasDetail").val("yes");
				  }else{
					  layer.msg(data.msg,{icon:2,time:1200});
				  }
			  }
		  });
	 }else{
	    layer.alert("单据已提交，不可再添加详情！");
	    return; 
	 }	  
  }
  //工具栏
	  $("#__toolbar__-c").iToolBar({
	   	 id:"__tb__01",
	   	 items:[
	   	  	{label:"删除", onclick:delDetail},
	    ]
	  });
	//删除物料详情
	function delDetail(){
	   var checkedNum = getGridCheckedNum("#grid-table-c", "id");
	   if(checkedNum==0){
	      layer.alert("请先选择要删除的详情！");
	      return;
	   }
	   if($("#setsForm #state").val()=="0"||$("#setsForm #state").val()==""){
	       var ids = jQuery("#grid-table-c").jqGrid("getGridParam", "selarrrow");
	   $.ajax({
	      url:context_path + "/setPull/delDetail.do?ids="+ids,
	      type:"POST",
	      dataType:"JSON",
	      success:function(data){
	         if(Boolean(data.result)){
	           layer.msg("操作成功！");
			   reloadDetailTableList();
			   $("#setsForm #hasDetail").val(data.hasDetail);
	         }else{
	           layer.msg(data.msg);
	         }
	      }
	   });	   
	   }else{
	     layer.alert("单据已提交，不可删除详情！");
	     return;	   
	   }   
	}
	 function reloadDetailTableList(){
          $("#grid-table-c").jqGrid("setGridParam", 
			    {
  	    			url:context_path + "/setPull/detailList.do?pId="+$("#setsForm #id").val(),
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}).trigger("reloadGrid");
     }
   $("#setsInfor").select2({
        placeholder: "选择套件",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width: 300,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/setPull/getSetsSelect",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                   // packageId:$("#setsForm #packageId").val(),
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                   
                    return {
                        results: res,
                        more: more
                    };
                      
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
   $("#setsForm #userId").select2({
        placeholder: "选择操作人",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width: 200,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/user/getUserSelect",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
	function finishOut(id){
	    $.ajax({
	       type:"post",
	       url:context_path+"/packageOut/finishOut.do?id="+id+"&packageId="+$("#setsForm #packageId").val()+"&outId="+$("#setsForm #id").val(),
	       dataType:"json",
	       success:function(data){
	            if(Boolean(data.result)){
	                layer.msg(data.msg,{icon:1});
	                reloadDetailTableList();
	                $("#grid-table").jqGrid("setGridParam", {
                    postData: {queryJsonString:""}
                   }).trigger("reloadGrid");
	            }else{
	                layer.msg(data.msg,{icon:2,time:2000});
	            }
	       }	    
	    });
	}
	function submit(){
	if($("#setsForm #id").val()==""){
	   layer.alert("请先保存表头信息！");
	   return;
	}
	if($("#setsForm #state").val()=="0"||$("#setsForm #state").val()==""){
	   layer.confirm("确定提交,提交之后数据不能修改", function () {
	   $.ajax({
	       type:"post",
	       url:context_path+"/setPull/submit.do?id="+$("#setsForm #id").val(),
	       dataType:"json",
	       success:function(data){
	           if(Boolean(data.result)){
	                layer.msg(data.msg,{icon:1});
	                $("#grid-table").jqGrid("setGridParam", {
                        postData: {queryJsonString:""}
                    }).trigger("reloadGrid");
                    $("#setsForm #state").val("1");	       
	           }else{
	                layer.msg(data.msg,{icon:2});
	           }	   
	        }	
	    });   
	 });	   
  }else{
	  layer.alert("单据已提交，请勿重复提交！");
      return;
	}
}
$.ajax({
	 type:"POST",
	 url:context_path + "/setPull/findSetById",
	 data:{id:$("#setsForm #id").val()},
	 dataType:"json",
	 success:function(data){
			 $("#setsForm #userId").select2("data", {
 			    id: data.userId,
 			    text: data.userName
             });
             $("#setsForm #carId").select2("data", {
 			    id: data.carId,
 			    text: data.carName
             }); 
		}
	});
</script>